#include "userslistviewer.h"
#include <QDebug>

UsersListViewer::UsersListViewer(UserList *List, QWidget *parent) :
    QComboBox(parent), m_list(List)
{
    refresh();
    model()->sort(0);
    setCurrentIndex(0);
    setEditable(true);
}

UsersListViewer::UsersListViewer(QWidget *parent):
    QComboBox(parent)
{}

void UsersListViewer::setUser(const int &Index)
{
    blockSignals(true);
    int id=findData(Index);
    if(id==-1)
    {
        User* user=m_list->user(Index);
        addItem(user->name(),user->id());
        id=findData(Index);
    }
    setCurrentIndex(id);
    blockSignals(false);
}

void UsersListViewer::setUsersList(UserList *list)
{
    m_list=list;
}

void UsersListViewer::uninclude(const int &uid)
{
    blockSignals(true);
    int index=findData(uid);
    if(index!=-1) removeItem(index);
    blockSignals(false);
}

void UsersListViewer::refresh()
{
    blockSignals(true);
    int uid=0;
    if(currentIndex()!=-1) uid = itemData(currentIndex()).toInt();
    clear();
    foreach(User* user,m_list->users(UserList::All))
    {
        if(user->isVisible()) addItem(user->name(),user->id());
    }    
    if(uid!=0)
    {
        uid=findData(uid);
        if(uid!=-1) setCurrentIndex(uid);
    }
    blockSignals(false);
}

void UsersListViewer::setFilter(const QString &unit)
{
    blockSignals(true);
    clear();
    QVector<int> uids = m_list->uidsByUnit(unit);
    foreach(User* user,m_list->users(UserList::All))
    {
        if(user->isVisible()&&(uids.indexOf(user->id())!=-1||uids.count()==0))
            addItem(user->name(),user->id());
    }
    model()->sort(0);
    blockSignals(false);
}



